package servlet;

import com.alibaba.fastjson.JSON;
import dao.CountMapper;


import org.apache.ibatis.session.SqlSession;
import pojo.Count;
import utils.MybatisUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;



@javax.servlet.annotation.WebServlet("/lifeServlet")
public class lifeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");  // 设置request字符编码
        response.setContentType("text/json; charset=utf-8");    // 设置response的编码及格式
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control","no-cache");
        PrintWriter out = response.getWriter();
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try {
            CountMapper CountMapper = sqlSession.getMapper(CountMapper.class);
            List<Count> countList = CountMapper.getCountList();

            String resJSON = JSON.toJSONString(countList);     // 转换为json
            out.print(resJSON);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
    }
}
